const ws = require('ws')
// const api=require('./api')
const createWSS = (server) => {
    const WS = ws.Server
    const wss = new WS({
        server
    })
    const users = {}
    const dataList = []
    wss.on('connection', (ws, req) => {
        const id = req.url.split('?')[1].split('=')[1]
        id && (users[id] = ws)

        //判断id是否存在 如果存在则不添加 不存在则添加
        if (!dataList.includes(id)) {
            dataList.push(id)
        } else {
            console.log('id已存在');
        }
        global.users = dataList
        console.log(global.users, 'global.users');

        Object.keys(users).forEach(userId => {
            //遍历除登录外的所有账号
            const datalist = global.users.filter(item => item !== userId)

            let currMeg = {
                type: 0,
                data: datalist
            }
            userId && users[userId].send(JSON.stringify(currMeg))
            console.log(datalist, '////////');
        })
        ws.on('message', (data) => {
            let msg = JSON.parse(data)
            console.log(msg, '////');
            if (msg.type === 1) {
                ws.send(JSON.stringify(msg))
                users[msg.data.toId] && users[msg.data.toId].send(JSON.stringify(msg))
            }
        })
    })
}
module.exports = createWSS